package game.module.mail.dao;

import game.module.mail.bean.MailList;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;

@Repository
public class MailDao {

	private LinkedBuffer buffer;

	@PostConstruct
	public void init() {
		buffer = LinkedBuffer.allocate(65536);
	}

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public int initMail(int roleId) {
		return jdbcTemplate.update("insert into mail(role_id) values(?)", roleId);
	}

	public void removeMailByRoleId(int roleId) {
		jdbcTemplate.update("delete from mail where role_id = ?", roleId);
	}

	public void saveMail(final int roleId, MailList mailList) {
		final InputStream inputStream;
		try {
			byte[] content = ProtostuffIOUtil.toByteArray(mailList, MailList.getSchema(), buffer);
			inputStream = new ByteArrayInputStream(content);
		} finally {
			buffer.clear();
		}
		jdbcTemplate.update("update mail set mail_blob = ? where role_id = ?", new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setBlob(1, inputStream);
				ps.setInt(2, roleId);
			}
		});
	}

	public MailList getMails(int roleId) {
		List<MailList> mailList = jdbcTemplate.query("select mail_blob from mail where role_id = ?", new Object[] { roleId }, new RowMapper<MailList>() {
			@Override
			public MailList mapRow(ResultSet rs, int rowNum) throws SQLException {
				MailList ml = new MailList();
				InputStream is = rs.getBinaryStream(1);
				try {
					ProtostuffIOUtil.mergeFrom(is, ml, MailList.getSchema());
				} catch (IOException e) {
					e.printStackTrace();
				}
				return ml;
			}
		});
		if (mailList == null || mailList.size() == 0) {
			return null;
		} else {
			return mailList.get(0);
		}
	}
}
